package ru.pashkan.spring.server;


import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.webapp.WebAppContext;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class EmbeddedWebServer implements InitializingBean, DisposableBean {

    Server jettyServer;

    @Autowired
    private CustomContextLoaderListener customContextLoaderListener;

    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println("Jetty Server: Start Server (" + getClass() + ")");

        jettyServer = new Server(8081);
        WebAppContext handler = new WebAppContext();
        handler.setDescriptor(getClass().getResource("/WEB-INF/web.xml").toString());
        handler.setResourceBase(getClass().getProtectionDomain().getCodeSource().getLocation().toString());
//        handler.setResourceBase(FileLocationHelper.getWebDir());
//        handler.addEventListener(customContextLoaderListener);
        handler.setContextPath("/");

        jettyServer.setHandler(handler);

        jettyServer.start();
//            jettyServer.join();
    }

    @Override
    public void destroy() throws Exception {
        jettyServer.stop();
    }
}

